<?php
namespace App\Modules\Order\Models;

use App\Exceptions\StandardException;
use App\Modules\Crowd\Models\Crowd;
use App\Modules\Payment\IOrder;
use App\Modules\Payment\Models\WeChatRefund;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Uuid;

/**
 * Class SupportOrder
 * @package App\Modules\Order\Models
 * @property string $pay_no
 * @property integer $user_id
 * @property integer $crowd_id
 * @property integer $price
 * @property integer $we_chat_pay
 * @property integer $we_chat_pay_time
 * @property integer $status
 * @property integer $content
 */
class SupportOrder extends Model implements IOrder
{
    const STATUS_INIT = "init";
    const STATUS_CLOSE = "close";
    const STATUS_SUCCESS = "success";
    const STATUS_REFUND = "refund";

    public static $showStatus = [
        self::STATUS_INIT => '待付款',
        self::STATUS_CLOSE => '已关闭',
        self::STATUS_SUCCESS => '成功',
        self::STATUS_REFUND => '退款',
    ];

    protected $fillable = [
        "pay_no",
        'user_id',
        'crowd_id',
        'price',
        'we_chat_pay',
        'we_chat_pay_time',
        'status',
        'content'
    ];

    public function getPrice()
    {
        return $this->price;
    }

    public function active(int $money)
    {
        DB::beginTransaction();
        $this->we_chat_pay = $this->price;
        $this->we_chat_pay_time = Carbon::now()->toDateTimeString();
        $this->status = self::STATUS_SUCCESS;
        /** @var Crowd $crowd */
        $crowd = Crowd::query()->find($this->crowd_id);
        $this->save();
        $crowd->support($this->user_id, $money);
        DB::commit();
    }

    public function getType()
    {
        return self::class;
    }

    public static function getNo()
    {
        return Uuid::uuid4()->getHex();
    }

    public function refund()
    {

        /** @var WeChatRefund $weChatRefund */
        $weChatRefund = WeChatRefund::query()->create([
            "order_type" => self::class,
            "order_id" => $this->id,
            'out_trade_no' => $this->pay_no,
            'out_refund_no' => Uuid::uuid4()->getInteger(),
            'total_fee' => $this->we_chat_pay,
            'refund_fee' => $this->we_chat_pay,
            'refund_desc' => "退款",
            'refund_account' => config('wechat.payment.refund_account', 'REFUND_SOURCE_UNSETTLED_FUNDS'),
            'status' => WeChatRefund::STATUS_INITIALIZED
        ]);
        if($weChatRefund->execute()) {
            $this->status = self::STATUS_REFUND;
            $this->save();
            return true;
        } else {
            return false;
        }
    }

    public function refundFail($money)
    {
        $this->status = self::STATUS_SUCCESS;
        $this->save();
    }
}
